package com.youlu.campus.service.ca;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.ca.UserCa;
import com.youlu.campus.entity.english.vo.response.CompetitionUserInviteResponse;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.activity.UserParticipateActivityInfoService;
import com.youlu.campus.service.ca.impl.CertificateActivityConfigService;
import com.youlu.campus.service.english.CompetitionUserInviteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;


@Service
@Slf4j
public class GenerateUserCaService {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityTaskService activityTaskService;

    @Autowired
    private CompetitionUserInviteService competitionUserInviteService;

    @Autowired
    private CertificateActivityConfigService certificateActivityConfigService;

    @Autowired
    private UserCaService userCaService;

    @Autowired
    private UserParticipateActivityInfoService userParticipateActivityInfoService;


    /**
     * 生成邀请电子证书
     * @param activityId
     * @param currentUser
     * @param point
     */
    @Async
    public void generateUserCa(String activityId,Integer point, UserPO currentUser){
        String userId = currentUser.getId();
        log.info("开始生成志愿者证书:{},{},{},{}", activityId,point, currentUser.getId(), currentUser.getCurrentPlatform());
        ActivityInfo activityInfo = activityService.findOne(activityId);
        String keyWord = activityInfo.getCaMatchKeyWords().get("invite");
        if (StringUtils.isBlank(keyWord)) {
            log.error(":>>> 活动:{} 没有配置证书匹配关键字", activityId);
            return;
        }
        if(Objects.isNull(point)||point==0){
            return;
        }
        UserParticipateActivityInfo userParticipateActivityInfo = userParticipateActivityInfoService.findByUserIdActivityId(userId, activityId);
        if(Objects.isNull(userParticipateActivityInfo)){
            log.error("用户-> {}未报名参与改活动-> {}",userId, activityId);
            return;
        }
        ActivityTaskInfo activityTaskInfo = activityTaskService.find(activityId, TaskBizType.INVITE);
        CompetitionUserInviteResponse competitionUserInvite = new CompetitionUserInviteResponse ();
        competitionUserInvite.setInviteValue(point);
        competitionUserInviteService.matchRule(activityTaskInfo,activityId,competitionUserInvite);
        String caLevel = competitionUserInvite.getCaLevel();
        if (StringUtils.isBlank(caLevel) ||"暂无证书".equals(caLevel)) {
            log.error(":>>> 用户:{} 活动:{} 获取暂无证书", userId, activityId);
            return;
        }
        UserCa userCa = new UserCa();
        //获取证书信息
        String matchesRegexKey = String.format(".*(%s).*", keyWord);
        log.info(":>>> 活动:{} 证书匹配表达式:{}", activityId, matchesRegexKey);
        String finalMatchesRegexKey = matchesRegexKey;
        List<CertificateActivityConfig> certificateActivityConfigList =
                certificateActivityConfigService.findByActivityId(activityId);
        Optional<CertificateActivityConfig> certificateActivityConfigOptional =
                certificateActivityConfigList.stream().filter(certificateActivityConfig -> certificateActivityConfig.getCertificateName().matches(finalMatchesRegexKey)).findAny();
        if (!certificateActivityConfigOptional.isPresent()) {
            log.error("【生成邀请电子证书配置不存在】-> userId - > {} caLevel-> {} activityId->{}", userId, caLevel
                    , activityId);
            return;
        }
        CertificateActivityConfig certificateActivityConfig = certificateActivityConfigOptional.get();
        String  caType = certificateActivityConfig.getCaType();
        UserCa userCaExist = userCaService.findByUserIdAndCaTypeAndCaLevel(userId, caType, caLevel, activityId);
        if (Objects.nonNull(userCaExist)) {
            log.error(":>>> 用户:{},类型:{}，等级:{},活动:{} 证书已经存在已经存在", userId, caType, caLevel, activityId);
            return;
        }
        userCa.setCertificateActivityConfigId(certificateActivityConfig.getId());
        userCa.setCaType(certificateActivityConfig.getCaType());
        userCa.setCertificateName(certificateActivityConfig.getCertificateName());

        userCa.setCaLevel(caLevel);
        userCa.setActivityId(activityId);
        userCa.setMoneyType("3");
        userCa.setActivityName(activityInfo.getName());
        userCa.setTaskBizType("invite");
        userCa.setUniversityId(userParticipateActivityInfo.getUniversityId());
        userCa.setUniversityName(userParticipateActivityInfo.getUniversityName());
        userCa.setName(userParticipateActivityInfo.getName());
        userCa.setMobile(userParticipateActivityInfo.getMobile());
        userCa.setGrade(userParticipateActivityInfo.getGrade());
        userCa.setUserId(userId);
        userCa.setScore(point.doubleValue());
        userCa.setPlatform(currentUser.getCurrentPlatform());
        userCa.setAppId(currentUser.getAppId());
        //生成用户证书信息
        log.info(":>>> 生成用户:{} 活动:{} 志愿者证书:{}", userCa, activityId, JSON.toJSONString(userCa));
        userCaService.create(userCa);

    }
}
